package com.lcz.audioplayer.service;

import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.widget.RemoteViews;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.bumptech.glide.Glide;
import com.lcz.audioplayer.MainActivity;
import com.lcz.audioplayer.NotificationReceiver;
import com.lcz.audioplayer.PlayerClient;
import com.lcz.audioplayer.PlayerManagerCallback;
import com.lcz.audioplayer.R;
import com.lcz.audioplayer.ScreenLockBroadcastReceiver;
import com.lcz.audioplayer.bean.AudioBean;
import com.lcz.audioplayer.util.ApplicationUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutionException;

public class PlayerService extends Service {

    private static String ACTION_START = "ACTION_START";
    /**
     * 歌曲播放
     */
    public static final String PLAY = "play";
    /**
     * 歌曲暂停
     */
    public static final String PAUSE = "pause";
    /**
     * 上一曲
     */
    public static final String PREV = "prev";
    /**
     * 下一曲
     */
    public static final String NEXT = "next";
    /**
     * 关闭通知栏
     */
    public static final String CLOSE = "close";
    static PlayerService mService = null;
    /**
     * 通知ID
     */
    private int NOTIFICATION_ID = 1;
    /**
     * 通知栏视图
     */
    private RemoteViews remoteViews;
    private NotificationReceiver notificationReceiver;
    private ScreenLockBroadcastReceiver screenLockBroadcastReceiver;
    /**
     * 通知管理器
     */
    private NotificationManager manager;
    /**
     * 通知
     */
    private Notification notification;
    PlayerClient playerClient;
    PlayerManagerCallback listener = new PlayerManagerCallback() {
        @Override
        public void onProgressChange(int currentProgress, int total, String currentPositionStr, String totalDurationStr) {

        }

        @Override
        public void onPlayStart() {
            updateNotificationShow();
        }

        @Override
        public void onPlayPause() {
            updateNotificationShow();
        }

        @Override
        public void onPlayStop() {

        }

        @Override
        public void onPlayError(MediaPlayer mp, int what, int extra) {

        }

        @Override
        public void onCompletion() {

        }
    };

    public static void startPlayerService() {
        if (mService != null) {
            return;
        }
        Intent intent = new Intent(ApplicationUtil.getCurApplication(), PlayerService.class);
        intent.setAction(ACTION_START);
        ApplicationUtil.getCurApplication().startService(intent);
    }


    @Override
    public void onCreate() {
        super.onCreate();
        mService = this;
        playerClient = PlayerClient.getInstance();
        playerClient.registerListener(listener);
        // 初始化EventBus
        EventBus.getDefault().register(this);
        registerNotificationReceiver();
        registerScreenLockReceiver();
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        //初始化RemoteViews配置
        initRemoteViews();
        //初始化通知
        initNotification();
        return START_NOT_STICKY;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String action) {

        switch (action) {
            case PLAY:
                //暂停或继续
                //如果现在的状态是正在播放的,那么就暂停
                if (playerClient.isPlaying()) {
                    playerClient.pause();
                } else {
                    //如果现在的状态是非播放的,那么我们就让播放器播放节目
                    playerClient.play();
                }
                break;
            case PREV:
                playerClient.playPre();
                break;
            case NEXT:

                playerClient.playNext();
                break;
            case CLOSE:

                closeNotification();
                break;
            default:
                break;
        }
    }

    /**
     * 关闭音乐通知栏
     */
    public void closeNotification() {
        if (playerClient != null) {
            if (playerClient.isPlaying()) {
                playerClient.pause();
            }
        }
        manager.cancel(NOTIFICATION_ID);

    }

    /**
     * 注册动态广播
     */
    private void registerNotificationReceiver() {
        notificationReceiver = new NotificationReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(PLAY);
        intentFilter.addAction(PREV);
        intentFilter.addAction(NEXT);
        intentFilter.addAction(CLOSE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            registerReceiver(notificationReceiver, intentFilter, RECEIVER_NOT_EXPORTED);
        } else {
            registerReceiver(notificationReceiver, intentFilter);
        }
    }
    private void unregisterNotificationReceiver() {
        if (notificationReceiver != null) {
            unregisterReceiver(notificationReceiver);
        }
    }
    /**
     * 注册锁屏动态广播
     */
    private void registerScreenLockReceiver() {
        screenLockBroadcastReceiver = new ScreenLockBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        //当屏幕灭了
        intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
        //当屏幕亮了
        intentFilter.addAction(Intent.ACTION_SCREEN_ON);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            registerReceiver(screenLockBroadcastReceiver, intentFilter, RECEIVER_NOT_EXPORTED);
        } else {
            registerReceiver(screenLockBroadcastReceiver, intentFilter);
        }
    }
    private void unregisterScreenLockReceiver() {
        if (screenLockBroadcastReceiver != null) {
            unregisterReceiver(screenLockBroadcastReceiver);
        }
    }



    /**
     * 初始化自定义通知栏 的按钮点击事件
     */
    private void initRemoteViews() {
        remoteViews = new RemoteViews(this.getPackageName(), R.layout.notification);

        //通知栏控制器上一首按钮广播操作
        Intent intentPrev = new Intent(PREV);
        PendingIntent prevPendingIntent = PendingIntent.getBroadcast(this, 0, intentPrev, PendingIntent.FLAG_IMMUTABLE);

        //为prev控件注册事件
        remoteViews.setOnClickPendingIntent(R.id.btn_notification_previous, prevPendingIntent);


        //通知栏控制器播放暂停按钮广播操作  //用于接收广播时过滤意图信息
        Intent intentPlay = new Intent(PLAY);
        PendingIntent playPendingIntent = PendingIntent.getBroadcast(this, 0, intentPlay, PendingIntent.FLAG_IMMUTABLE);
        //为play控件注册事件
        remoteViews.setOnClickPendingIntent(R.id.btn_notification_play, playPendingIntent);

        //通知栏控制器下一首按钮广播操作
        Intent intentNext = new Intent(NEXT);
        PendingIntent nextPendingIntent = PendingIntent.getBroadcast(this, 0, intentNext, PendingIntent.FLAG_IMMUTABLE);
        //为next控件注册事件
        remoteViews.setOnClickPendingIntent(R.id.btn_notification_next, nextPendingIntent);

        //通知栏控制器关闭按钮广播操作
        Intent intentClose = new Intent(CLOSE);
        PendingIntent closePendingIntent = PendingIntent.getBroadcast(this, 0, intentClose, PendingIntent.FLAG_IMMUTABLE);
        //为close控件注册事件
        remoteViews.setOnClickPendingIntent(R.id.btn_notification_close, closePendingIntent);

    }

    /**
     * 初始化通知
     */
    private void initNotification() {
        String channelId = "play_control";
        String channelName = "播放控制";
        int importance = NotificationManager.IMPORTANCE_HIGH;
        createNotificationChannel(channelId, channelName, importance);

        //点击整个通知时发送广播
//        Intent intent = new Intent(getApplicationContext(), NotificationClickReceiver.class);
//        PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0,
//                intent, PendingIntent.FLAG_UPDATE_CURRENT);
        Intent intent = this.getPackageManager().getLaunchIntentForPackage(ApplicationUtil.getCurApplication().getPackageName());
        PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_IMMUTABLE);

        //初始化通知
        notification = new NotificationCompat.Builder(this, "play_control")
                .setContentIntent(pendingIntent)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.icon_big_logo)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.icon_big_logo))
                .setCustomContentView(remoteViews)
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setAutoCancel(false)
                .setOnlyAlertOnce(true)
                .setOngoing(true)
                .build();
    }

    /**
     * 更改通知的信息和UI
     */
    public void updateNotificationShow() {
        AudioBean audioBean = playerClient.getAudioList().get(playerClient.getCurrentIndex());
        //播放状态判断
        if (playerClient.isPlaying()) {
            remoteViews.setImageViewResource(R.id.btn_notification_play, R.drawable.pause_black);
        } else {
            remoteViews.setImageViewResource(R.id.btn_notification_play, R.drawable.play_black);
        }
        //封面专辑
//        remoteViews.setImageViewBitmap(R.id.iv_album_cover, null);


        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Bitmap bitmap = Glide.with(PlayerService.this)
                            .asBitmap()
                            .load(audioBean.getImage())
                            .submit()
                            .get();
                    remoteViews.setImageViewBitmap(R.id.iv_album_cover, bitmap);
                    manager.notify(NOTIFICATION_ID, notification);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();


        //歌曲名
        remoteViews.setTextViewText(R.id.tv_notification_song_name, audioBean.getName());
        //歌手名
        remoteViews.setTextViewText(R.id.tv_notification_singer, "刘德华");
        //发送通知
        manager.notify(NOTIFICATION_ID, notification);

    }

    /**
     * 创建通知渠道
     *
     * @param channelId   渠道id
     * @param channelName 渠道名称
     * @param importance  渠道重要性
     */
    @TargetApi(Build.VERSION_CODES.O)
    private void createNotificationChannel(String channelId, String channelName, int importance) {
        NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
        channel.enableLights(false);
        channel.enableVibration(false);
        channel.setVibrationPattern(new long[]{0});
        channel.setSound(null, null);
        manager = (NotificationManager) getSystemService(
                NOTIFICATION_SERVICE);
        manager.createNotificationChannel(channel);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mService = null;
        EventBus.getDefault().unregister(this);
        stopForeground(true);
        unregisterNotificationReceiver();
        unregisterScreenLockReceiver();
        playerClient.unRegisterListener(listener);
    }
}